<!-- MessageList.vue 消息列表组件 -->
<template>
	<div class="message-list" ref="scrollContainer">
		<MessageItem
			v-for="message in messages"
			:id="`message-${message.id}`"
			:key="message.id"
			:message="message"
			:current-user="currentUser"
			:target-user="targetUser"
			:class="{ 'current-playing': message.id === curMsgId }"
		/>
		<p v-show="messages.length === 0" class="empty-message">
			<i class="iconfont icon-queshengye_zanwuxiaoxi"></i>
			<span>对话记录出逃了~</span>
		</p>
	</div>
</template>

<script setup>
	import { ref } from 'vue'
	import MessageItem from './MessageItem.vue'
	// ===========================================DATA======================================================
	const props = defineProps({
		messages: { type: Array, required: true },
		currentUser: { type: Object, required: true },
		targetUser: { type: Object, required: true },
		curMsgId: { type: String, required: true }
	})

	const scrollContainer = ref()
	// ===========================================METHODS==================================================
	// 添加滚动到指定消息的方法
	const scrollToMessage = (messageId) => {
		// console.log('messageId: ', messageId)
		if (!scrollContainer.value) return

		// 获取消息元素
		const messageEl = document.getElementById(`message-${messageId}`)

		if (!messageEl) return

		// 获取消息列表容器
		const container = scrollContainer.value
		// 获取容器的可视区域高度
		const containerHeight = container.clientHeight

		// 获取消息元素的位置信息
		const messageRect = messageEl.getBoundingClientRect()
		const containerRect = container.getBoundingClientRect()

		// 计算消息元素相对于容器的顶部位置
		const messageTop = messageRect.top - containerRect.top

		// 如果消息在可视区域外，则滚动到该消息
		// 只有当消息不在第一屏时才滚动
		if (messageTop < 0 || messageTop > containerHeight) {
			// 平滑滚动到消息位置，保持在容器中间
			container.scrollTo({
				top: messageEl.offsetTop - containerHeight / 2 + 30, //+30保证底部露出半截的高亮信息全部展示
				behavior: 'smooth'
			})
		}
	}
	// ===========================================OTHERS==================================================
	// 暴露方法给父组件
	defineExpose({
		scrollToMessage
	})
</script>

<style lang="less" scoped>
	.message-list {
		padding: 10px;
		background: #f3f3f3;
		border-radius: 2px;
		min-height: calc(100vh - 380px);
		height: calc(100vh - 380px);
		overflow-y: auto;
		&::-webkit-scrollbar {
			width: 8px;
		}
		&::-webkit-scrollbar-track {
			background: #f0f0f0;
		}
		&::-webkit-scrollbar-thumb {
			background: #d6d6d6;
			border-radius: 4px;
		}
		&::-webkit-scrollbar-thumb:hover {
			background: #ccc;
		}
		// 添加当前播放消息的高亮样式
		.current-playing {
			background-color: rgba(87, 148, 247, 0.1) !important;
			border-left: 3px solid #5794f7 !important;
			transition: background-color 0.3s ease;
		}
		.empty-message {
			flex: 1;
			height: 95%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			.icon-queshengye_zanwuxiaoxi {
				font-size: 64px;
			}
			span {
				font-size: 14px;
				color: #999;
			}
		}
	}
</style>
